package gaobo.tree;

import java.util.*;

public class MyBinaryTree {

    //节点内部类
    static class TreeNode {
        public int val;
        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode createTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    //二叉树遍历
    //1.前序遍历
    //根->左子树->右子树
    //2.中序遍历
    //左-根-右
    //3.后续遍历
    //左-右-根

    //前序遍历
    public void preOrder(TreeNode root){
        if (root == null){
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //中序遍历
    public void inOrder(TreeNode root){
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val +" ");
        inOrder(root.right);
    }

    //后序遍历
    public void postOrder(TreeNode root){
        if (root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");

    }

    //前序遍历并存储【力扣144】
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        ret.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        ret.addAll(leftTree);

        List<Integer> rightTree = preorderTraversal(root.right);
        ret.addAll(rightTree);
        return ret;
    }

    //获取数中节点的个数
    //遍历法
    public static int nodeSize = 0;
    public int size(TreeNode root){
        if (root == null){
            return 0;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
        return nodeSize;
    }
    //子问题拓展
    public int size2(TreeNode root){
        if (root == null){
            return 0;
        }
        int tmp = size2(root.left) + size2(root.right) + 1;
        return tmp;
    }

    //获取叶子节点的个数
    //子问题拓展
    public int getLeafNodeCount(TreeNode root){
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        int tmp = getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
        return tmp;
    }
    //遍历法
    public static int leafSize = 0;
    public void getLeafNodeCount2(TreeNode root){
        if (root == null){
            return;
        }
        if (root.left == null && root.right == null){
            leafSize++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

    //获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root,int k){
        if (root == null || k <= 0){
            return 0;
        }
        if (k == 1){
            return 1;
        }
        int tmp = getKLevelNodeCount(root.left,k-1) +
                getKLevelNodeCount(root.right,k-1);
        return tmp;
    }

    //获取二叉树的高度
    public int getHeight(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1;
    }

    //检测值为value的元素是否存在
    public TreeNode find(TreeNode root, char val){
        if (root == null){
            return null;
        }
        if (root.val == val){
            return root;
        }
        TreeNode ret1 = find(root.left,val);
        if (ret1 != null){
            return ret1;
        }
        TreeNode ret2 = find(root.right,val);
        if (ret2 != null){
            return ret2;
        }
        return null;
    }


    //判断相同的树【力扣100】 时间复杂度 O(min(M,N))
    public boolean isSameTree(TreeNode p, TreeNode q){
        if (p == null && q != null || p != null && q == null){
            return false;
        }
        if (p == null && q == null){
            return true;
        }
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //另一棵树的子树【力扣572】
    // 时间复杂度:O(r*s)  root: r个节点  subRoot: s个节点
    public boolean isSubtree(TreeNode root, TreeNode subRoot){
        //空指针异常
        if (root == null || subRoot == null)
            return false;
        //1.判断两棵树是不是相同的树
        if (isSameTree(root,subRoot))
            return true;
        //2.subRoot 是不是 root.left 的子树
        if (isSubtree(root.left,subRoot))
            return true;
        //3.subRoot 是不是 root.right 的子树
        if (isSubtree(root.right,subRoot))
            return true;
        return false;
    }

    //反转二叉树【力扣226】
    public TreeNode invertTree(TreeNode root){
        if (root == null){
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //平衡二叉树【力扣110】
    //要判断整棵树是高度平衡的二叉树，那么必须满足
    //每棵子树都必须是高度平衡的二叉树

    //思路:先求当前root节点是不是平衡的
    //再去判断左树是不是平衡的
    //再去判断右树是不是平衡的
    //时间复杂度 O(N^2)
    public boolean isBalanced(TreeNode root){
        if (root == null) return true;
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);

        return Math.abs(leftH-rightH) < 2 &&
                isBalanced(root.left) &&
                isBalanced(root.right);
    }

    //如何让时间复杂度为O(N)
    //在求高度时加判断
    public int maxDepth(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        if (leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight-rightHeight) <= 1){
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            return -1;
        }
    }
    public boolean isBalancedOptimize(TreeNode root){
        if (root == null) return true;
        return maxDepth(root) >= 0;
    }

    //对称二叉树 力扣【101】
    //检查轴对称二叉树
    //思路:root左树和root右树是否对称(相等)
    public boolean isSymmetric(TreeNode root){
        if (root == null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);

    }

    private boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree){
        if (leftTree == null && rightTree != null ||
        leftTree != null && rightTree == null){
            return false;
        }
        if (leftTree == null && rightTree == null){
            return true;
        }
        if (leftTree.val != rightTree.val){
            return false;
        }
        return isSymmetricChild(leftTree.left,rightTree.right) &&
        isSymmetricChild(leftTree.right,rightTree.left);
    }


    //层序遍历（非递归）
    public void levelOrder(TreeNode root){
        if (root == null){
            return;
        }
        //运用队列
        Queue<TreeNode> qu = new LinkedList<>();
        qu.offer(root);
        while (!qu.isEmpty()){
            TreeNode cur = qu.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null){
                qu.offer(cur.left);
            }
            if (cur.right != null){
                qu.offer(cur.right);
            }
        }
    }

    //层序遍历 力扣【102】 分层存储
    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        //如何确定每一层
        if (root == null) {
            return list;
        }
        Queue<TreeNode> qu = new LinkedList<>();
        qu.offer(root);
        while (!qu.isEmpty()) {
            int size = qu.size();
            List<Integer> tmp = new ArrayList<>();
            while (size > 0) {
                TreeNode cur = qu.poll();
                size--;
                tmp.add(cur.val);
                if (cur.left != null) {
                    qu.offer(cur.left);
                }
                if (cur.right != null) {
                    qu.offer(cur.right);
                }
            }
            list.add(tmp);
        }
        return list;
    }

    //判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if (root == null){
            return true;
        }
        Queue<TreeNode> qu = new LinkedList<>();
        qu.offer(root);
        while (!qu.isEmpty()) {
            TreeNode cur = qu.poll();
            if (cur != null){
                qu.offer(cur.left);
                qu.offer(cur.right);
            }else {
                break;
            }
        }
        //判断队列剩下的值是否有 非null 的数据
        while (!qu.isEmpty()){
            TreeNode pop = qu.poll();
            if (pop != null){
                return false;
            }
        }
        return true;
    }

    //构建二叉树及遍历 牛客【KY11】
    private static int i = 0;
    public static TreeNode createTree2(String str){
        TreeNode root = null;
        if (str.charAt(i) != '#'){
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree2(str);
            root.right = createTree2(str);
        }else {
            i++;
        }
        return root;
    }

    //二叉树的最近公共祖先 力扣【236】
    //给定一个二叉树,找到该树中两个指定节点的最近公共祖先

    //思路1:
    //如果每个节点 有父亲节点的地址/关系  此时就是求链表的交点
    //当前不知道父亲节点的关系，可以先定义两个栈 存放p，q走过的路径所有节点
    //让多的先出差值个节点 再同时出判断何时出相等
    //此时问题:如何去存储 根节点到 p或者q 路径上的所有节点？

    //只要root不为空 就往栈里面放
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        if (root == null || p == null || q == null){
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root,p,stack1);

        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack2);

        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2){
            int size = size1 - size2;
            while (size > 0){
                stack1.pop();
                size--;
            }
        }else {
            int size = size2 - size1;
            while (size > 0){
                stack2.pop();
                size--;
            }
        }
        //两个栈当中一定是相同的节点个数
        //前提两个都不为空
        while (stack1.peek() != stack2.peek()){
            stack1.pop();
            stack2.pop();
        }
        return stack1.peek();


    }
    //存储给定节点走过的路径
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode > stack){
        if (root == null || node == null){
            return false;
        }
        stack.push(root);
        if (root == node){
            return true;
        }
        boolean flg1 = getPath(root.left,node,stack);
        if (flg1 == true){
            return true;
        }
        boolean flg2 = getPath(root.right,node,stack);
        if (flg2 == true){
            return true;
        }
        stack.pop();
        return false;
    }

    //思路2:
    // 二叉搜索数/二叉查找树:根节点的左边都比根节点小 根节点的右边都比根节点大
    // 特点:中序遍历是有序的
    public TreeNode lCA(TreeNode root, TreeNode p, TreeNode q){
        if (root == null){
            return null;
        }
        //先判断根
        if (root == p || root == q){
            return root;
        }
        //根不是 判断左边
        TreeNode leftTree = lCA(root.left,p,q);
        //左边不是判断右边
        TreeNode rightTree = lCA(root.right,p,q);
        if (leftTree != null && rightTree != null){
            return root;
        }
        else if (leftTree != null/*&& rightTree == null */){
            return leftTree;
        }
        else if (rightTree != null/*&& leftTree == null */){
            return rightTree;
        }//如果两边都不是
        else {
            return null;
        }
    }

    //二叉搜索树与双向链表 牛客【JZ36】
    //注意:不能创建任何新的节点 只能调整树中节点指针的指向
    //1.怎么有序？ 中序遍历
    //2.二叉搜索树 如何解决 前驱和后继的问题？

    TreeNode prev = null;
    public TreeNode convert(TreeNode root){
        if (root == null){
            return null;
        }
        convertChild(root);
        TreeNode head = root;
        while (head.left != null){
            head = head.left;
        }
        return head;
    }

    private void convertChild(TreeNode pCur){
        if (pCur == null){
            return;
        }
        convertChild(pCur.left);
        //System.out.print(pCur.val + " ");
        pCur.left = prev;
        if (prev != null){
            prev.right = pCur;
        }
        prev = pCur;
        convertChild(pCur.right);
    }


    //非递归实现前序遍历 【力扣144】
    public List<Integer> preorderTraversalNor(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;

        }
        return ret;
    }

    //非递归实现中序遍历 【力扣94】
    public List<Integer> inorderTraversalNor(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            ret.add(top.val);
            //System.out.print(top.val + " ");
            cur = top.right;
        }
        return ret;
    }

    //非递归实现后序遍历【力扣145】
    public List<Integer> postorderTraversalNor(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                ret.add(top.val);
                //System.out.print(top.val + " ");
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return ret;
    }

    //根据一棵树的前序遍历与中序遍历构建二叉树【力扣105】
    public TreeNode buildTree(int[] preorder, int[] inorder){
        return buildTreeChild(preorder,0,inorder,0,inorder.length-1);
    }
    private TreeNode buildTreeChild(int[] preorder, int preIndex,
                                    int[] inorder,int inbegin, int inend){
        //1.判断当前根节点是不是还有 左子树 或者 右子树
        if (inbegin > inend){
            return null;
        }

        //创建根节点
        TreeNode root = new TreeNode((char) preorder[preIndex]);
        //2.找到root在中序遍历的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        if (rootIndex == -1){
            return null;
        }
        //构建左子树和右子树
        root.left = buildTreeChild(preorder,preIndex,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,preIndex,inorder,rootIndex+1,inend);
        return root;
    }
    private int findIndex(int[] inorder,int inbegin, int inend,int val){
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    //根据一棵树的中序遍历与后序遍历构建二叉树【力扣106】

    public int postIndex;
    public TreeNode buildTree2(int[] inorder, int[] postorder){
        postIndex = postorder.length-1;
        return buildTreeChild2(postorder,inorder,0,inorder.length-1);
    }
    private TreeNode buildTreeChild2(int[] postorder, int[] inorder,int inbegin, int inend){
        //1.判断当前根节点是不是还有 左子树 或者 右子树
        if (inbegin > inend){
            return null;
        }

        //创建根节点
        TreeNode root = new TreeNode(postorder[postIndex]);
        //2.找到root在中序遍历的位置
        int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;
        if (rootIndex == -1){
            return null;
        }
        //构建左子树和右子树
        root.right = buildTreeChild(postorder,postIndex,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,postIndex,inorder,inbegin,rootIndex-1);

        return root;
    }
    private int findIndex2(int[] inorder,int inbegin, int inend,int val){
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    //二叉树创建字符串【力扣606】
    public String tree2str(TreeNode root){
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);

        return stringBuilder.toString();

    }
    public void tree2strChild(TreeNode t, StringBuilder stringBuilder){
        if (t == null){
            return;
        }
        stringBuilder.append(t.val);

        if (t.left != null){
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if (t.right == null){
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        if (t.right == null){
            return;
        }else {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }
    }
}
